<?php

namespace apiend\models;

use Yii;
use common\helpers\FileHelper;
use common\helpers\IpHelper;
use common\models\Attachment;

/**
 * 图片上传模型
 * UploadImage is the model behind the upload form.
 */
class UploadImage extends \common\base\Model {

    use \common\traits\Constants;

    const SCOPE_DEFAULT = 'default';
    const SCOPE_USER = 'user';
    const SCOPE_COURSE = 'course';

    /**
     * @name $user_id
     * @var integer 用户UID
     */
    public $user_id = 0;

    /**
     * @name $scope
     * @var string 应用范围
     */
    public $scope = 'default';

    /**
     * @name $imageFile 待上传文件
     * @var \yii\web\UploadedFile file attribute
     */
    public $imageFile = null;

    /**
     * @name $channel
     * @var string 上传通道，支持通道阿里云OSS:、服务器SFTP
     */
    public $channel = 'OSS';

    /**
     * @name $cut
     * @var integer 是否启用图片压缩
     */
    public $cut = 0;

    /**
     * @name $uploadPath
     * @var string 上传根目录别名
     */
    public $uploadPath = '@uploads';

    /**
     * @return array the validation rules.
     */
    public function rules() {
        return [
            [['user_id'], 'integer'],
            ['scope', 'in', 'range' => static::getConstants(), 'message' => '{attribute}不在允许范围内'],
            [['imageFile'], 'file', 'mimeTypes' => 'image/jpeg, image/png, image/gif, image/bmp'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'user_id' => '用户ID',
            'scope' => '应用场景',
            'imageFile' => '文件',
        ];
    }

    public function upload() {
        if (!$this->validate()) {
            $this->dumpError('上传校验失败', $this->getFirstErrors());
        }

        $relativeDir = '/attachments/' . $this->scope . '/' . date('Ym/d') . '/';
        $absoluteDir = Yii::getAlias($this->uploadPath . $relativeDir);
        FileHelper::dirCreate($absoluteDir);

        $file = $this->imageFile;
        list($width, $height, $type) = getimagesize($file->tempName);
        if (!$type) {
            $this->dumpError('图片格式错误');
        }
        $extension = $file->extension ?: image_type_to_extension($type);

        $filename = FileHelper::generateUploadFileName($extension);

        $file->saveAs($absoluteDir . $filename);

        $relativePath = $relativeDir . $filename;

        if ($file->getHasError()) {
            $this->dumpError('文件保存失败', $file->error);
        }

        $attachs = new Attachment();
        $attachs->attributes = [
            'user_id' => $this->user_id,
            'path' => $relativePath,
            'original_name' => $file->name,
            'channel' => $this->channel,
            'size' => $file->size,
            'isimage' => 1,
            'width' => $width,
            'height' => $height,
            'ip' => IpHelper::ip(),
        ];
        $attachs->setToken();
        if (!$attachs->save()) {
            return $attachs->getErrors();
        }
        return $attachs;
    }

}
